import os
import CSYNAC.Lib as lab


class File():
    def __init__(self,path:list,):
        self._path:list = path
        self._get_info()
        self.verbose("start")
        self._md5:str

    def _get_info(self):
        pass

    def rpath(self):
        return '.' if len(self._path)==1 else os.path.join(*self._path[1:])

    def apath(self):
        if len(self._path)==1:
            return self._path[0]
        else:
            return os.path.join(*self._path)

    def name(self):
        return self._path[-1]

    def Basefolder(self):
        return self._path[0]

    def depth(self):
        return len(self._path)-1

    def verbose(self, verbose):
        pass

    def md5(self):
        if not hasattr(self,'_md5'):
            self._md5 = lab.md5_file(self.apath())
        return self._md5


class Folder(File):
    def __init__(self,path):
        super(Folder,self).__init__(path)
        self.subFiles:dict = {}
        self.subFolders:dict = {}
        self.verbose("Folder_init")

    def md5(self):
        if not hasattr(self,'_md5'):
            self._md5 = lab.md5_folder(self.apath())
        return self._md5

    def subfiles(self):
        return [file for file in os.listdir(self.apath())
                if os.path.isfile(self.path_of_subfile(file))]

    def subfolders(self):
        return [folder for folder in os.listdir(self.apath())
                if os.path.isdir(self.path_of_subfolder(folder=folder))]

    def path_of_subfile(self,file)->str:
        return os.path.join(*self._path,file)

    def path_of_subfolder(self, folder)->str:
        return os.path.join(*self._path,folder)

    def processing_files(self):
        for file in self.subfiles():
            path = self._path[:]
            path.append(file)
            self.subFiles[file]=File(path)

    def processing_folders(self):
        for folder in self.subfolders():
            path = self._path[:]
            path.append(folder)
            self.subFolders[folder] = Folder(path) # type:Folder
            self.subFolders[folder].analyze()

    def analyze(self):
        self.processing_files()
        self.processing_folders()

    def execute(self,f):
        f(self)
        for file in self.subFiles:
            f(self.subFiles[file])
        for folder in self.subFolders:
            self.subFolders[folder].execute(f)


class SFolder(Folder):
    def __init__(self,path:str,nickname:str="SynacFolder"):
        self.nackname = nickname
        self.flags:dict = {}
        self.flags['inited'] = False
        self.folders:dict = {}
        spath = [os.path.abspath(path),]
        super(SFolder,self).__init__(spath)

    def analyze(self):
        super(SFolder,self).analyze()
        self.flags['inited'] = True

    def r_to_apath(self,rpath):
        apath = os.path.join(self._path[0],rpath)
        try:
            assert os.path.exists(apath)
        except:
            print("")
        return apath


# if __name__ == '__main__':